package cc.market.service.impl;

import cc.market.mapper.UserMapper;
import cc.market.service.UserService;
import cc.market.DTO.UserDTO;
import cc.market.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    /**
     * 用户注册
     * @param userDTO
     * @return
     */
    @Override
    public Boolean register(UserDTO userDTO) {

        //先校验有无phone用户存在
        if(userMapper.getByPhone(userDTO.getPhone()) != null){
            return false;
        }
        //对象属性拷贝
        User user = User.builder()
                        .status((byte) 0)
                        .build();
        BeanUtils.copyProperties(userDTO, user);
        user.setNickName(userDTO.getPhone()); // 初始的昵称设置为手机号
        // 对密码进行 bcrypt 加密
        String encryptedPassword = passwordEncoder.encode(userDTO.getPassword());
        user.setPassword(encryptedPassword);

        // 设置时间字段
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        log.info("准备mapper插入：",user);
        int res = userMapper.addUser(user);
        return res > 0;
    }

    /**
     * 根据手机号查找
     * @param phone
     * @return
     */
    @Override
    public User getByPhone(String phone) {
        return userMapper.getByPhone(phone);
    }

    @Override
    public User getById(Integer userId) {
        return userMapper.getById(userId);
    }

    @Override
    public void update(User user) {
        userMapper.update(user);
    }

    @Override
    public void updatePwd(Integer id,String pwd) {
        // 对密码进行 bcrypt 加密
        String encryptedPassword = passwordEncoder.encode(pwd);
        userMapper.updatePwd(id,encryptedPassword);
    }
}
